﻿using System;
using System.Collections.Generic;
using Microsoft.EntityFrameworkCore;
using SimpleWebApi.MyMigration.Models;
using SimpleWebApi.MyMigration.Models.BusinessLicenseManagement;

namespace SimpleWebApi.MyMigration
{

    public class AdvancedCustomerDbContext : DbContext
    {
        public AdvancedCustomerDbContext()
        {
        }

        public AdvancedCustomerDbContext(DbContextOptions<AdvancedCustomerDbContext> options)
            : base(options)
        {
        }        

        public virtual DbSet<BusinessLicense> BusinessLicenses { get; set; }
        public virtual DbSet<LegalPerson> LegalPersons { get; set; }
        public virtual DbSet<RelatedPerson> RelatedPersons { get; set; }

        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
            => optionsBuilder.UseMySql(
            "Server=127.0.0.1;Port=3307;Database=AdvancedCustomerDB;User=root;Password=790727wyP.;CharSet=utf8mb4;", // 连接字符串
            ServerVersion.AutoDetect("Server=127.0.0.1;Port=3307;Database=AdvancedCustomerDB;User=root;Password=790727wyP.;CharSet=utf8mb4;") // 自动检测版本
        );

        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            modelBuilder.Entity<BusinessLicense>(entity =>
            {
                // 强制 LegalPerson 为必填 (Required)
                entity.HasOne(bl => bl.LegalPerson)
                    .WithMany(lp => lp.BusinessLicenses)
                    .HasForeignKey(bl => bl.LegalPersonId)
                    .OnDelete(DeleteBehavior.Restrict)
                    .IsRequired(); // 添加 IsRequired()
                
        

                // 调整中间表配置为可选
                modelBuilder.Entity<BusinessLicenseRelatedPerson>()
                    .HasKey(blrp => new { blrp.BusinessLicenseId, blrp.RelatedPersonId });

                modelBuilder.Entity<BusinessLicenseRelatedPerson>()
                    .HasOne(blrp => blrp.BusinessLicense)
                    .WithMany(bl => bl.RelatedPersons)
                    .HasForeignKey(blrp => blrp.BusinessLicenseId)
                    .OnDelete(DeleteBehavior.Cascade); // 允许删除许可证时级联删除关联

                modelBuilder.Entity<BusinessLicenseRelatedPerson>()
                    .HasOne(blrp => blrp.RelatedPerson)
                    .WithMany(rp => rp.BusinessLicenses)
                    .HasForeignKey(blrp => blrp.RelatedPersonId)
                    .OnDelete(DeleteBehavior.Restrict);
            

                // 企业信用代码唯一约束
                entity.HasIndex(e => e.CreditCode).IsUnique();

                // 枚举字段存储为字符串
                entity.Property(e => e.CompanyType)
                    .HasConversion<string>()
                    .HasMaxLength(20);

                // 外键关系配置
                entity.HasOne(bl => bl.LegalPerson)
                    .WithMany(lp => lp.BusinessLicenses)
                    .HasForeignKey(bl => bl.LegalPersonId)
                    .OnDelete(DeleteBehavior.Restrict); // 阻止级联删除                
            });

            modelBuilder.Entity<LegalPerson>(entity =>
            {

                modelBuilder.Entity<LegalPerson>(entity =>
                {
                    entity.HasIndex(p => p.IdNumber)
                        .IsUnique(); // 唯一索引
                });

                // 枚举字段存储为字符串
                //entity.Property(e => e.EducationLevel)
                //    .HasConversion<string>()
                //    .HasMaxLength(20);
                // 一对多关系
                entity.HasMany(lp => lp.BusinessLicenses)
                    .WithOne(bl => bl.LegalPerson)
                    .HasForeignKey(bl => bl.LegalPersonId)
                    .OnDelete(DeleteBehavior.Cascade); // 级联删除
            });

            modelBuilder.Entity<RelatedPerson>(entity =>
            {
                entity.HasIndex(p => p.IdNumber)
                    .IsUnique();
            });

            modelBuilder.Entity<Commodity>(entity =>
            {
                entity.ToTable("Commodity");

                entity.Property(e => e.ImageUrl)
                    .HasMaxLength(1000)
                    .IsUnicode(false);
                entity.Property(e => e.Price).HasColumnType("decimal(18, 2)");
                entity.Property(e => e.Title)
                    .HasMaxLength(500)
                    .IsUnicode(false);
                entity.Property(e => e.Url)
                    .HasMaxLength(1000)
                    .IsUnicode(false);
            });

            modelBuilder.Entity<CompanyInfo>(entity =>
            {
                entity.HasKey(e => e.CompanyId).HasName("PK_Company");

                entity.ToTable("CompanyInfo");

                entity.Property(e => e.CreateTime).HasColumnType("datetime");
                entity.Property(e => e.LastModifyTime).HasColumnType("datetime");
                entity.Property(e => e.Name)
                    .HasMaxLength(50)
                    .IsUnicode(false);
            });

            modelBuilder.Entity<SysUser>(entity =>
            {
                entity.ToTable("SysUser");

                entity.Property(e => e.Address)
                    .HasMaxLength(500)
                    .IsUnicode(false);
                entity.Property(e => e.CreateTime).HasColumnType("datetime");
                entity.Property(e => e.Email)
                    .HasMaxLength(50)
                    .IsUnicode(false);
                entity.Property(e => e.LastLoginTime).HasColumnType("datetime");
                entity.Property(e => e.LastModifyTime).HasColumnType("datetime");
                entity.Property(e => e.Mobile)
                    .HasMaxLength(12)
                    .IsUnicode(false);
                entity.Property(e => e.Name)
                    .HasMaxLength(50)
                    .IsUnicode(false);
                entity.Property(e => e.Password)
                    .HasMaxLength(50)
                    .IsUnicode(false);
                entity.Property(e => e.Phone)
                    .HasMaxLength(12)
                    .IsUnicode(false);
                entity.Property(e => e.Qq).HasColumnName("QQ");
                entity.Property(e => e.WeChat)
                    .HasMaxLength(50)
                    .IsUnicode(false);

                entity.HasOne(d => d.Company).WithMany(p => p.SysUsers)
                    .HasForeignKey(d => d.CompanyId)
                    .OnDelete(DeleteBehavior.Cascade)
                    .HasConstraintName("FK_SysUser_CompanyInfo");
            });

            OnModelCreatingPartial(modelBuilder);
        }

        public void OnModelCreatingPartial(ModelBuilder modelBuilder)
        {

        }

        // 中间实体（自动生成表）
        public class BusinessLicenseRelatedPerson
        {
            public int BusinessLicenseId { get; set; }
            public BusinessLicense BusinessLicense { get; set; }

            public int RelatedPersonId { get; set; }
            public RelatedPerson RelatedPerson { get; set; }
        }
    }
}